package com.xx.sg.schedule;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.xx.sg.own.entity.Dept;
import com.xx.sg.own.entity.FireInfo;
import com.xx.sg.own.service.DeptService;
import com.xx.sg.own.service.FireInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HkFireInfoTask {

    @Value("${hk.host}")
    private String HK_HOST;
    @Value("${hk.key}")
    private String HK_KEY;
    @Value("${hk.secret}")
    private String HK_SECRET;
    @Value("${hk.artemis-path}")
    private String ARTEMIS_PATH;

    @Autowired
    private DeptService deptService;
    @Autowired
    private FireInfoService fireInfoService;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void synBaseData() throws Exception {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(HK_HOST); // 代理API网关nginx服务器ip端口
        config.setAppKey(HK_KEY);  // 秘钥appkey
        config.setAppSecret(HK_SECRET);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/bforestfire/v1/alarms/judge/list";

        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        JSONObject param = new JSONObject();
        param.put("pageNo", 1);
        param.put("pageSize", 1000);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                .withZone(ZoneOffset.UTC);
        String startTime = LocalDateTime.now()
                .minusMinutes(6L)
                .atZone(ZoneId.of("Asia/Shanghai"))
                .withZoneSameInstant(ZoneOffset.UTC)
                .format(formatter);
        param.put("beginTime", startTime);
        System.out.println(param.toString());
        String response = ArtemisHttpUtil.doPostStringArtemis(config, path, param.toString(),
                null, null, "application/json;charset=UTF-8");
        JSONObject result = JSONObject.parseObject(response);
        JSONArray list = result.getJSONObject("data").getJSONArray("list");
        for (int i = 0; i < list.size(); i++) {
            JSONObject item = list.getJSONObject(i);
            String sourceId = item.getString("id");
            LambdaQueryWrapper<FireInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FireInfo::getSourceId, sourceId)
                    .eq(FireInfo::getClassify, "video");
            List<FireInfo> fireInfoList = fireInfoService.list(wrapper);
            if (fireInfoList.isEmpty()) {

                Instant instant = Instant.parse(item.getString("startTime"));
                // 转换为东八区时间
                LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));

                FireInfo fireInfo = FireInfo.builder()
                        .sourceId(sourceId)
                        .datetime(dateTime)
                        .name(item.getString("eventName"))
                        .longitude(item.getDouble("longitude"))
                        .latitude(item.getDouble("latitude"))
                        .classify("video")
                        .picture(item.getString("picUrls"))
                        .build();

                Dept dept = deptService.selectDeptByPoint(fireInfo.getLongitude(), fireInfo.getLatitude());
                if (dept == null) {
                    fireInfo.setRegionId("00115");
                } else {
                    fireInfo.setRegionId(dept.getId());
                }
                fireInfoService.save(fireInfo);
            }
        }
    }
}
